package com.samsung.handler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.protocol.HTTP;
import org.apache.http.util.EncodingUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlSerializer;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Xml;

import com.samsung.sbackup.FragmentSettingsPreference;

public class SmsHandler {
	public volatile int progress = 0;
	public Cursor c;
	String file = "";
	String Path;
	public int totalMessage;
	NodeList nList;
	boolean isError;
	String errorMessage;

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public boolean isError() {
		return isError;
	}

	public void setError(boolean isError) {
		this.isError = isError;
	}

	Context context;
	ContentResolver cr;
	SharedPreferences sharedPref;

	public String getFile() {
		return file;
	}

	public void setFile(String file) {
		this.file = file;
	}

	public SmsHandler(Context ctx) {
		setError(false);
		setErrorMessage("No errors");
		this.context = ctx;
		cr = context.getContentResolver();
		sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
		String folder = sharedPref.getString(
				FragmentSettingsPreference.BACKUP_PATH, "/");

		SimpleDateFormat sf = new SimpleDateFormat("HHmmddMMyyyy",
				Locale.getDefault());
		String date = sf.format(Calendar.getInstance().getTime());
		setFile(folder + "/sms_" + date + ".xml");
		String[] PROJECTION = new String[] { "_id", "thread_id", "address",
				"date", "type", "body", "read", "service_center", "seen" };
		Uri uri = Uri.parse("content://sms");
		c = cr.query(uri, PROJECTION, null, null, null);
	}

	public SmsHandler(String Path, Context ctx)
			throws ParserConfigurationException {
		this.context = ctx;
		cr = context.getContentResolver();
		this.Path = Path;

		File fXmlFile = new File(this.Path.replaceFirst("zip", "xml"));
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc;
		try {
			doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();
			nList = doc.getElementsByTagName("sms");
			totalMessage = nList.getLength();
		} catch (Exception e) {
			e.printStackTrace();
			setError(true);
			setErrorMessage("Error: " + e.toString());
		}
	}

	public void backup(ContentResolver cr) {
		try {
			FileOutputStream fos = new FileOutputStream(new File(getFile()));
			XmlSerializer serializer = Xml.newSerializer();
			serializer.setFeature(
					"http://xmlpull.org/v1/doc/features.html#indent-output",
					true);
			serializer.setOutput(fos, "UTF-8");
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", "allSms");
			writeSms(cr, fos, serializer);
			serializer.endTag("", "allSms");
			serializer.endDocument();
			serializer.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
			setError(true);
			setErrorMessage("Error: " + e.toString());
		}
	}

	public void restore(ContentResolver cr) {
		boolean checkDate = true;
		ContentValues values = new ContentValues();
		try {
			Cursor c = cr.query(Uri.parse("content://sms"), new String[] {
					"_id", "date" }, null, null, null);
			ArrayList<String> arrayList = new ArrayList<String>();
			c.moveToFirst();
			while (c.moveToNext()) {
				arrayList.add(c.getString(c.getColumnIndexOrThrow("date")));
			}

			for (int temp = 0; temp < nList.getLength(); temp++) {
				checkDate = true;
				progress = temp + 1;
				Node nNode = nList.item(temp);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) nNode;
					values.put("address", "" + eElement.getAttribute("address"));
					values.put("body", "" + eElement.getAttribute("body"));
					values.put("type", "" + eElement.getAttribute("type"));
					values.put("date", "" + eElement.getAttribute("date"));
					for (int i = 0; i < arrayList.size(); i++) {
						if (eElement.getAttribute("date").equals(
								arrayList.get(i))) {
							checkDate = false;
							System.out.println(false);
							break;
						}
					}
					values.put("read", "" + eElement.getAttribute("read"));
					values.put("seen", "" + eElement.getAttribute("seen"));
					values.put("service_center",
							"" + eElement.getAttribute("service_center"));
					values.put("date_sent",
							"" + eElement.getAttribute("date_sent"));
					if (checkDate == true)
						cr.insert(Uri.parse("content://sms"), values);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			setError(true);
			setErrorMessage("Error: " + e.toString());
		}
	}

	public void writeSms(ContentResolver cr, FileOutputStream fos,
			XmlSerializer serializer) throws InterruptedException {

		if (c.moveToLast())
			do {
				progress++;
				try {
					serializer.startTag("", "sms");
					serializer.attribute("", "thread_id",
							String.valueOf(c.getString(1)));
					serializer.attribute("", "address",
							String.valueOf(c.getString(2)));
					serializer.attribute("", "date",
							String.valueOf(c.getString(3)));
					serializer.attribute("", "type",
							String.valueOf(c.getString(4)));
					String s = c.getString(5);

					// check for replacement character and replace with 'space'
					// character
					boolean bool = false;
					byte[] b = s.getBytes();
					for (int i = 0; i < b.length; i++) {
						if ((i > 0) && (i < b.length - 1) && (b[i - 1] == -16)
								&& (b[i] == -97) && (b[i + 1] == -104)) {
							b[i - 1] = 32;
							b[i] = 32;
							b[i + 1] = 32;
							b[i + 2] = 32;
							bool = true;
						}
					}

					String s1 = EncodingUtils.getString(b, HTTP.UTF_8);
					if (bool) {
						serializer.attribute("", "body", s1);
					} else {
						serializer.attribute("", "body", s);
					}
					serializer.attribute("", "read",
							String.valueOf(c.getString(6)));
					serializer.attribute("", "service_center",
							String.valueOf(c.getString(7)));
					serializer.attribute("", "seen",
							String.valueOf(c.getString(8)));
					serializer.endTag("", "sms");
				} catch (IOException e) {
					e.printStackTrace();
					setError(true);
					setErrorMessage("Error: " + e.toString());
				}
			} while (c.moveToPrevious());
	}

}
